#Author：雨霁夜茶

import requests
import json
import re
import time
import threading
data_dict={}
keys=set()
import numpy as np
data_value=0

lock = threading.RLock()
def load_zb():
    try:
        res = requests.get("https://trans.zb.com/line/topall?jsoncallback=jQuery1910048297495833478754_1510822168037&_=1510822168038")
        lock.acquire()
        text=res.text.replace('jQuery1910048297495833478754_1510822168037(','').replace(')','')
        text = json.loads(text)
        count = len(text['datas'])
        btc_price=0

        for i in range(count):
            content = text['datas'][i]
            data_value = float(content['lastPrice'])

            if '/USDT' in content['marketShowName']:
                key = content['marketShowName'].replace('/USDT', '').lower()
                if key == 'btc':
                    data_dict[key] = {'usdt': data_value, 'btc': 1, 'precent': 0}
                    btc_price = data_value
                    break

        for i in range(count):
            content = text['datas'][i]
            # print(content['MarketName'],content['Last'])
            data_value=float(content['lastPrice'])
            key=content['marketShowName'].lower().split('/')[0]
            if '/USDT' in content['marketShowName']:
                keys.add(key)
                data_dict[key]={'key':key,'usdt':data_value,'btc':0,'precent':0}
        for i in range(count):
            content = text['datas'][i]
            # print(content['MarketName'],content['Last'])
            data_value = float(content['lastPrice'])
            key = content['marketShowName'].lower().split('/')[0]
            if '/BTC' in content['marketShowName']:
                keys.add(key)
                if data_dict.get(key) != None:
                    data_dict.get(key)['btc'] = data_value
                    # print(data_dict_bittrex.get(key))
                else:
                    data_dict[key] = {'key': key, 'usdt': data_value * btc_price, 'btc': data_value,
                                              'precent': 0}
        data_dict['btc']['btc']=1
        lock.release()
        print('下载成功：ZB')
        return data_dict,keys
    except requests.exceptions.RequestException:
        print('RequestException ZB')
        return data_dict, keys
    except requests.exceptions.ConnectionError:
        print('ConnectionError ZB')
        return data_dict, keys
    except :
        print('Error ZB')
        return data_dict, keys

if __name__ == "__main__":
    load_zb()
    for k,v in data_dict.items():
        print(k,':',v)